from django.core.exceptions import ValidationError
from django.core.files.storage import Storage
from django.conf import settings
from fdfs_client.client import Fdfs_client


class FastDFSStorage(Storage):
    def __init__(self, fdfs_base_url=None):
        self.fdfs_base_url = fdfs_base_url or settings.FDFS_BASE_URL

    def _open(self, name, mode='rb'):
        # 功能：打开django本地文件
        pass

    def _save(self, name, content, max_length=None):
        # 功能：在ImafeField类型字段被赋值为一个文件对象的时触发调用保存文件
        # 参数：@name文件名；@content文件对象
        # 提取文件数据
        # data =content.read()
        # # 上传
        # conn = Fdfs_client(settings.FDFS_PATH)
        # ret = conn.upload_by_buffer(data)
        # if ret['Status'] != 'Upload successed.':
        #     raise ValidationError('上传失败')
        # file_id = ret['Remote file_id']
        # return file_id
        pass

    def exists(self, name):
        # 功能:用于判断保存文件是否重复
        pass

    def url(self, name):
        return self.fdfs_base_url + name